package com.common.login;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.java.member.vo.MemberVO;


public class CheckLocaleInterceptor extends HandlerInterceptorAdapter {

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		if(modelAndView == null)
			return;
//		System.out.println("세션정보 입력");
		
		Map<String, MemberVO> sessionMap = new HashMap<String, MemberVO>();
		HttpSession session  = request.getSession();
		
		//세션정보 설정
		sessionMap.put("id",(MemberVO)session.getAttribute("login_info"));
		modelAndView.addObject("sessionMap", sessionMap);
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String rootPath = request.getContextPath();
		String loginPath = rootPath + "/memberLogin.do";
		
		String url = request.getRequestURI();
//		System.out.println("=] URL : "+ url);
		
		if(loginPath.equals(url)){
//			System.out.println("============4==============");
			return true;
		}
		
//		System.out.println("=] session check");
		
		HttpSession session = request.getSession(false);
		
		if(session == null){
			response.sendRedirect(loginPath);
			return false;
		}
		
		if(!hasSessionInfo(request.getSession())){
			response.sendRedirect(loginPath);
			return false;
		}
		
		return true;
	}

	/**
	 * 세션에 로그인 정보가 있는지 확인한다. 
	 */
	private boolean hasSessionInfo(HttpSession session){
		return (session.getAttribute("login_info") != null);
	}
}

